import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import '../../widgets/tags/icon.dart';
import '../../widgets/tags/title.dart';
import '../../application.dart';
import '../../widgets/tags/empty.dart';
import '../../models/article_model.dart';
import '../../models/detail_arguments.dart';
import '../../utils/api.dart';
import '../../utils/tools.dart';

class DetailPage extends StatefulWidget {
  final DetailArguments arguments;

  const DetailPage({Key key, this.arguments}) : super(key: key);

  @override
  _DetailPageState createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  String _title = "文章详情";
  int id = 0;
  bool isLoading = true;
  ArticleModel article;

  String title;
  String cover;

  bool isFavourite = false;
  bool isDigg = false;

  ScrollController _scrollController;
  bool titleMode = false;
  double swipeHeight = 300;

  @override
  void initState() {
    super.initState();
    var arguments = widget.arguments;

    if (arguments.temp != null) {
      if (arguments.temp is Map<String, dynamic>) {
        var art = arguments.temp;
        this.title = art['title'];
        this.cover = art['cover'];
      } else if (arguments.temp is ArticleModel) {
        article = arguments.temp;
        title = article.title;
        cover = article.cover;
      }
    }

    _scrollController = ScrollController();
    _scrollController.addListener(_onScroll);

    if (arguments.id != null) {
      this.id = arguments.id;
      _loadData();
    }
  }

  _onScroll() {
    if (_scrollController.offset > swipeHeight - 50) {
      if (!titleMode && article != null) {
        setState(() {
          titleMode = true;
        });
      }
    } else {
      if (titleMode) {
        setState(() {
          titleMode = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    swipeHeight = MediaQuery.of(context).size.width * 0.6;

    return Scaffold(
      extendBodyBehindAppBar: true,
      body: CustomScrollView(
        controller: _scrollController,
        slivers: <Widget>[
          SliverAppBar(
            pinned: true,
            backgroundColor: Colors.white,
            expandedHeight: swipeHeight,
            leading: IconButton(
              onPressed: () {
                Application.back(context);
              },
              icon: TagIcon(
                Icons.arrow_back,
                size: 24,
                color: titleMode ? Colors.black87 : Colors.white,
                shadows: titleMode
                    ? null
                    : [
                        Shadow(
                            color: Color.fromRGBO(0, 0, 0, 0.8),
                            offset: Offset.zero,
                            blurRadius: 10)
                      ],
              ),
            ),
            title: Text(
              titleMode ? title : '',
              maxLines: 1,
              style: TextStyle(color: Colors.black87),
              overflow: TextOverflow.ellipsis,
            ),
            flexibleSpace: FlexibleSpaceBar(
              background: (article.images == null || article.images.isEmpty)
                  ? Tools.image(article.cover)
                  : _buildSwipe(context),
              //titlePadding: EdgeInsets.only(right: 50.0),
              //centerTitle: true,
              collapseMode: CollapseMode.parallax,
            ),
          ),
          SliverList(
              delegate: SliverChildListDelegate([
            Center(
              child: TagTitle(title, fontSize: 24,),
            ),
            Center(
              child: RichText(
                text: TextSpan(
                  children: [
                    TextSpan(text:'类目:'),
                    TextSpan(text:article.cateId.toString()),
                    TextSpan(text:' 发布日期:'),
                    TextSpan(text: Tools.formatDateFromTimestamp(article.createTime)),
                    TextSpan(text:' 浏览:'),
                    TextSpan(text:article.views.toString()),
                ],
                style: TextStyle(color: Colors.black38,fontSize: 13)
                ),
                softWrap: false,
              ),
            ),
            Container(
              padding: EdgeInsets.all(10),
              child: (article.content == null || article.content.isEmpty)
                  ? (isLoading?Center(child: CircularProgressIndicator()):TagEmpty('暂无内容~',icon: null,))
                  : Html(
                      data: article.content,
                    ),
            )
          ])),
        ],
      ),
    );
  }

  _buildSwipe(BuildContext context) {
    return Swiper(
      itemBuilder: (BuildContext context, idx){
        return Tools.image(article.images[idx].image);
      },
      itemCount: article.images.length,
      control: SwiperControl(),
    );
  }

  _loadData() async {
    Api.post('article/view', {'id': this.id}).then((result) {
      var data = result.data;
      if (data == null) return;
      if (!mounted) return;
      setState(() {
        
        var pdata = result.data['article'];
        pdata['images'] = result.data['images'];
        article = ArticleModel.fromJson(pdata);
        title = article.title;
        cover = article.cover;

        isFavourite = result.data['is_favourite'] == 1;
        isDigg = result.data['digged'] == 1;
        isLoading = false;
      });
    });
  }
}
